package com.restphp.java.hashdb.utils;

import java.io.*;

/**
 * Created by sofical on 2020/7/31.
 */
public class FileUtils {
    /**
     * 写文件.
     * @param content 内容.
     * @param savePath 保存路径.
     */
    public static void save(String content, String savePath) {
        BufferedWriter writer = null;
        try {
            //目标文件组成
            //检查是否存在，不存在创建.
            File file = new File(savePath);
            Boolean sleep = false;
            if(!file.exists()){
                sleep = true;
                file.createNewFile();
            }
            //写内容
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            writer.write(content);
            writer.flush();
            writer.close();
            if (sleep) {
                Thread.sleep(500);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != writer) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取文件内容
     * @param filePath 文件路径.
     * @return 文件内容.
     */
    public static String get(String filePath) {
        File file = new File(filePath);
        String content = "";
        if(!file.exists()){
            return null;
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                content += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content;
    }
}
